package com.lch.webdemo.config;

import com.lch.webdemo.aop.MultipleDataSource;
import com.lch.webdemo.enums.DataSourceEnum;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import tk.mybatis.spring.annotation.MapperScan;

/**
 * <一句话描述>.
 *
 * @author liuchenhui
 * @date 2018/10/19
 * @since
 */
@Configuration
@AutoConfigureAfter({DataSourceConfig.class})
@Import({DataSourceConfig.class})
@MapperScan(basePackages = {"com.lch.webdemo.dao"})
public class SqlSessionFactoryConfig {

    @Resource(name = "masterDataSource")
    private DataSource masterDataSource;

    @Resource(name = "slaveDataSource")
    private DataSource slaveDataSource;

    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(roundRobinDataSouceProxy());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/*.xml"));
        sessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        return sessionFactory.getObject();
    }

    @Bean
    public AbstractRoutingDataSource roundRobinDataSouceProxy() {
        MultipleDataSource proxy = new MultipleDataSource();
        Map<Object, Object> targetDataResources = new HashMap<>(2);
        targetDataResources.put(DataSourceEnum.MASTER, masterDataSource);
        targetDataResources.put(DataSourceEnum.SLAVE, slaveDataSource);
        //默认源
        proxy.setDefaultTargetDataSource(masterDataSource);
        proxy.setTargetDataSources(targetDataResources);
        return proxy;
    }

}
